"use client" // 带布局系统的组件必须声明为客户端组件
import Link from 'next/link'
import React, { useEffect, useMemo, useState } from 'react'
import { Button, Layout, Typography, Dropdown, Space, Modal, Form, Input, message, Popover, Menu, Image } from 'antd'
import { AppstoreFilled, BarChartOutlined, createFromIconfontCN, DownOutlined, ExclamationCircleOutlined, GlobalOutlined, HomeFilled, HomeOutlined, MedicineBoxFilled, MenuFoldOutlined, MenuUnfoldOutlined, PlusSquareFilled, RadarChartOutlined, SettingFilled, UserOutlined } from '@ant-design/icons'
import { postAdminUpdatePwdApi, getAdminInfoApi } from '@/apis/login'
import { useRouter } from 'next/navigation'
import { baseUrl } from '@/apis/login'
const { Title } = Typography;

// const { Header, Footer, Sider, Content } = Layout;
const MyIcons = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_4677211_uc30srbz3ah.js'
})

const iconMap = {
  home: <HomeOutlined />,
  building: <RadarChartOutlined/>,
  medical: <MedicineBoxFilled/>,
  category: <AppstoreFilled/>,
  chart: <BarChartOutlined/>,
  basic: <GlobalOutlined/>,
  layers: <SettingFilled/>,
}
export default function adminLayout({ children }) {
  const [form] = Form.useForm()
  const submit = async (e) => {
    const token = localStorage.getItem('adminToken')
    console.log(e);
    const res = await postAdminUpdatePwdApi(e.oldPassword, e.newPassword, token)
    const resObj = await res.json()
    console.log(resObj)
    if (resObj.code === 2000) {
      message.success('修改密码成功')
      setShowModel(false)
    } else {
      message.error(`密码修改失败！服务器返回错误消息${resObj.msg}`)
    }
    form.resetFields()
  }
  const changePwd = () => {
    console.log('修改密码')
    setShowModel(true)
  }
  const items = [
    {
      label: (
        <div onClick={changePwd}>修改密码</div>
      ),
      key: '0',
    },
    {
      label: (
        <div>个人资料</div>
      ),
      key: '1',
    },
  ]
  // 初始皮肤颜色
  const [skin, setSkin] = useState('#0e4a93')
  // 可选的皮肤颜色
  const [skins, setSkins] = useState(['#0e4a93', '#f00', '#99f', '#669', '#080', '#826cde'])
  const contentInfo = (
    <Space style={{ display: 'flex' }}>
      {skins.map(item => (<div onClick={() => setSkin(item)} key={item} style={{ cursor: 'pointer', width: '60px', height: '30px', backgroundColor: item }}></div>))}
    </Space>
  )

  const [showModel, setShowModel] = useState(false)
  const [show, setShow] = useState(false)

  const [adminInfo, setAdminInfo] = useState({})
  const router = useRouter()

  const getPrivilegesList = (arr) => {
    const newArr = []
    for (const item of arr) {
      const children = getPrivilegesList(item.children).length > 0 ? getPrivilegesList(item.children) : null
      newArr.push({
        key: `${item.pid}-${item.path}`,
        icon: iconMap[item.icon] || null,
        // pid: item.pid, 
        label: item.pname,
        children
      })
    }
    return newArr
  }

  // 功能列表
  const privilegesList = useMemo(() => {
    return getPrivilegesList(adminInfo?.privileges || [])
  }, [adminInfo])

  useEffect(() => {
    ; (async () => {
      const res = await getAdminInfoApi()
      const resObj = await res.json()
      console.log(resObj)
      if (resObj.code) {
        Modal.info({
          title: '提示',
          content: '您尚未登录或登录超时，请重新登录',
          okText: '去登陆',
          onOk: () => {
            router.push('/')
          }
        })
        return
      }
      setAdminInfo(resObj)
    })()
    router.push('/admin')
  }, [])
  // 菜单项
  const menuItems = [
    {
      key: 'sub1',
      label: '首页',
      icon: <HomeFilled />,
      children: []
    },
    {
      key: 'sub2',
      label: '智慧物业',
      icon: <HomeFilled />,
      children: [
        {
          key: 'sub2-1',
          label: '物业缴费'
        },
        {
          key: 'sub2-2',
          label: '缴费查询'
        },
        {
          key: 'sub2-3',
          label: '故障报修'
        }
      ]
    },
    {
      key: 'sub3',
      label: '社区医疗',
      icon: <MedicineBoxFilled />,
      children: [
        {
          key: 'sub3-1',
          label: '社区挂号'
        },
        {
          key: 'sub3-2',
          label: '健康小贴士'
        },
        {
          key: 'sub3-3',
          label: '医生介绍'
        }
      ]
    }
  ]
  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 左侧功能菜单 */}
      <Layout.Sider trigger={null} style={{ color: '#fff', backgroundColor: skin }} collapsible collapsed={show} >
        <Menu mode='inline' items={privilegesList} onClick={e => router.push(e.key.split('-')[1])}
          style={{ backgroundColor: skin, color: '#fff' }}
          theme='dark'
          defaultSelectedKeys={['1-/admin']}
        />
      </Layout.Sider>
      {/* 右侧顶部导航+页面主题 */}
      <Layout style={{ minWidth: '950px' }}>
        <Layout.Header style={{ display: 'flex', paddingLeft: 0, color: '#fff', backgroundColor: skin, marginLeft: '2px' }}>
          {/* <button onClick={() => setShow(!show)}>收起或展开</button> */}
          {/* <Button type='text'>按钮</Button> */}
          <Button
            onClick={() => setShow(!show)}
            type='text'
            icon={show ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            style={{ fontSize: '16px', width: '64px', height: '64px', color: '#fff' }}
          />
          <div style={{ color: '#fff', height: '100%' }}>
            <img style={{ marginTop: '5%', height: '80%', width: 'auto' }} src='/img/u811.png' />
          </div>
          <div style={{ display: 'flex', flex: 1, justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', marginLeft: '10px', flex: 1 }}><Title level={2} style={{ margin: 0, color: '#fff' }}>天通苑智慧社区管理系统</Title></div>
            <div style={{ display: 'flex', flexWrap: 'nowrap' }}>
              <Dropdown
                menu={{
                  items,
                }}
                trigger={['click']}
              >
                <a style={{ color: '#fff', display: 'flex', alignItems: 'center', display: 'inline-block' }} onClick={(e) => e.preventDefault()}>
                  <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', height: '64px' }}>
                    <MyIcons type='icon-user' style={{ fontSize: '20px' }} />
                    <span style={{ padding: '0 5px', boxSizing: 'border-box', display: 'inline-block', height: '64px' }}>{adminInfo.userName || '用户名'}</span>
                    <DownOutlined />
                  </div>
                </a>
              </Dropdown>
              <Popover content={contentInfo} trigger="click">
                <a style={{ marginLeft: '25px', color: '#fff', display: 'flex', alignItems: 'center', display: 'inline-block' }} onClick={(e) => e.preventDefault()}>
                  <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', height: '64px' }}>
                    <MyIcons type='icon-colorpad' style={{ fontSize: '20px', marginRight: '5px' }} />
                    <span style={{ padding: '0 5px', boxSizing: 'border-box', display: 'inline-block', height: '64px' }}>换肤</span>
                    {/* <DownOutlined /> */}
                  </div>
                </a>
              </Popover>
              <Dropdown
                menu={{
                  items,
                }}
                trigger={['click']}
              >
                <a style={{ marginLeft: '25px', color: '#fff', display: 'flex', alignItems: 'center', display: 'inline-block' }} onClick={(e) => e.preventDefault()}>
                  <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', height: '64px' }}>
                    <MyIcons type='icon-help' style={{ fontSize: '20px' }} />
                    <span style={{ padding: '0 5px', boxSizing: 'border-box', display: 'inline-block', height: '64px' }}>帮助</span>
                    <DownOutlined />
                  </div>
                </a>
              </Dropdown>
              <a onClick={() => Modal.confirm({
                title: '确认',
                content: '确认要退出吗',
                icon: <ExclamationCircleOutlined />,
                okText: '确定',
                onOk: () => {
                  localStorage.removeItem('adminToken')
                  localStorage.removeItem('adminToken2')
                  router.replace('/')
                },
                cancelText: '取消'
              })} style={{ marginLeft: '25px', color: '#fff', display: 'flex', alignItems: 'center', display: 'inline-block' }}>
                <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', height: '64px' }}>
                  <MyIcons type='icon-off' style={{ fontSize: '20px' }} />
                  {/* <span style={{ padding: '0 5px', boxSizing: 'border-box', display: 'inline-block', height: '64px' }}>Hover me</span> */}
                  {/* <DownOutlined /> */}
                </div>
              </a>
            </div>
          </div>
        </Layout.Header>
        <Layout.Content style={{ backgroundColor: '#f5f5f5' }}>{children}</Layout.Content>
      </Layout>
      <Modal title="修改密码" open={showModel} onCancel={() => setShowModel(false)} okText="确定" cancelText="取消"
        okButtonProps={{
          autoFocus: true,
          htmlType: 'submit',
        }}
        modalRender={(dom) => (
          <Form
            form={form}
            name="form_in_modal"
            onFinish={(values) => submit(values)}
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 20,
            }}
          >
            {dom}
          </Form>
        )}
      >
        <Form.Item
          label="旧密码"
          name="oldPassword"
          rules={[
            {
              required: true,
              message: '请输入旧密码',
            },
          ]}
        >
          <Input.Password placeholder='请输入旧密码' />
        </Form.Item>
        <Form.Item
          label="新密码"
          name="newPassword"
          rules={[
            {
              required: true,
              message: '请输入新密码',
            },
          ]}
        >
          <Input.Password placeholder='请输入新密码' />
        </Form.Item>
        <Form.Item
          label="确认密码"
          name="confirmPassword"
          dependencies={['newPassword']}
          rules={[
            {
              required: true,
              message: '请再次输入密码',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码不一致!'));
              },
            }),
          ]}
        >
          <Input.Password placeholder='请再次输入密码' />
        </Form.Item>
      </Modal>
    </Layout>
  )
}
